from fastapi import APIRouter
from app.api.deps import CurrentUser, SessionDep
from app.crud.uc.partner_token import update_partner_token, get_partner_token
from app.schemas.uc.partner_token import PartnerTokenUpdate, PartnerTokenPublic
from app.schemas.xm.xm_user import XmUserCreate, XmUserUpdate, XmUserPublic
from app.crud.xm.xm_user import create_user_xm, update_user_xm, get_user_xm

router = APIRouter(tags=["xm-user"], prefix="/xm-user")

@router.post("/refresh_token", response_model=PartnerTokenPublic)
async def xm_token_refresh(
    session: SessionDep,
    current_user: CurrentUser,
    xmToken: str
):
    """
    刷新XM Token
    """
    return await update_partner_token(
        session=session,
        uid=current_user.uid,
        partner=1,
        partner_token=PartnerTokenUpdate(
            accessToken=xmToken,
        )
    )

@router.get("/token", response_model=PartnerTokenPublic)
async def xm_token(
    session: SessionDep,
    current_user: CurrentUser
):
    """
    获取XM Token
    """
    return await get_partner_token(
        session=session,
        uid=current_user.uid,
        partner=1,
    )

@router.post("/", response_model=XmUserPublic)
async def create_new_user_xm(
    session: SessionDep,
    current_user: CurrentUser,
    user_xm_create: XmUserCreate
):
    """
    保存xm用户信息
    """
    user_xm_create.internalUid = current_user.uid
    return await create_user_xm(
        session=session,
        user_xm=user_xm_create,
    )

@router.post("/update", response_model=XmUserPublic)
async def update_existing_user_xm(
    session: SessionDep,
    current_user: CurrentUser,
    user_xm_update: XmUserUpdate
):
    """
    更新xm用户信息
    """
    return await update_user_xm(
        session=session,
        internal_uid=current_user.uid,
        user_xm=user_xm_update,
    )

@router.get("/", response_model=XmUserPublic)
async def get_existing_user_xm(
    session: SessionDep,
    current_user: CurrentUser,
):
    """
    获取xm用户信息
    """
    return await get_user_xm(
        session=session,
        internal_uid=current_user.uid,
    )